Because
XNA 2D programming is almost entirely a process of moving sprites
around the screen, you might expect that loading and drawing bitmaps in
an XNA program is fairly easy, and you would be correct.
The first project is called XnaLocalBitmap,
so named because this bitmap will be stored as part of the program’s
content. To add a new bitmap to the program’s content project,
right-click the XnaLocalBitmapContent project name, select Add and then
New Item, and then Bitmap File. You can create the bitmap right in
Visual Studio.
Or, you can create the bitmap
in an external program, as I did. Windows Paint is often convenient, so
for this exercise I created the following bitmap with a dimension of
320 pixels wide and 160 pixels high:
I saved it under the name Hello.png.
To add this
file as part of the program’s content, right-click the
XnaLocalBitmapContent project in Visual Studio, select Add and Existing
Item, and then navigate to the file. Once the file shows up, you can
right-click it to display Properties, and you’ll see that it has an
Asset Name of “Hello.”
The goal is to display this bitmap centered on the screen. Define a field in the Game1.cs file to store the Texture2D and another field for the position:
Example 1. XNA Project: XnaLocalBitmap File: Game1.cs (excerpt showing fields)
public class Game1 : Microsoft.Xna.Framework.Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; Texture2D helloTexture; Vector2 position; . . . }
|
Both fields are set during the LoadContent method. Use the same generic method to load the Texture2D as you use to load a SpriteFont. The Texture2D class has properties named Width and Height that provide the dimensions of the bitmap in pixels. The position field indicates the pixel location on the display that corresponds to the upper-left corner of the bitmap:
Example 2. XNA Project: XnaLocalBitmap File: Game1.cs (excerpt)
protected override void LoadContent() { spriteBatch = new SpriteBatch(GraphicsDevice); helloTexture = this.Content.Load<Texture2D>("Hello"); Viewport viewport = this.GraphicsDevice.Viewport; position = new Vector2((viewport.Width - helloTexture.Width) / 2, (viewport.Height - helloTexture.Height) / 2); }
|
The SpriteBatch class has seven Draw methods to render bitmaps. This one is certainly the simplest:
Example 3. XNA Project: XnaLocalBitmap File: Game1.cs (excerpt)
protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(Color.Navy);
spriteBatch.Begin(); spriteBatch.Draw(helloTexture, position, Color.White); spriteBatch.End();
base.Draw(gameTime); }
|
The final argument to Draw is a color that can be used to attenuate the existing colors in the bitmap. Use Color.White if you want the bitmap’s colors to display without any alteration.
And here it is: